var _config ;

var pandianid = GetQueryString('pandianid');
var shopcode = sessionStorage.getItem("shopcode");
var userId = sessionStorage.getItem("userId");
var pingjiaFlag = GetQueryString("pingjiaFlag");
var rate;
layui.use(['rate'], function(){
	 rate = layui.rate;
	});
$(document).ready(function(){
	/*if(type=='1'){
		$('#touxiang').text(decodeURI(decodeURI(username)));
	}else{
		$('#touxiang').text(decodeURI(decodeURI(username)).substring(decodeURI(decodeURI(username)).length-2,decodeURI(decodeURI(username)).length));
	}*/
	if(sessionStorage.getItem("reload")=='true'){
	     window.location.reload();
		sessionStorage.setItem("reload", false);
		console.log("reload"); 
	}else{
		$('#name').text(sessionStorage.getItem("name"));
		//未评价
		if(pingjiaFlag == '0'){
			getPandianPingjiaItem();
			$('#saveButton').show();
		}else{
			getPandianPingjia();
			$('#saveButton').hide();
		}
		
		$('#saveButton').on('click',saveInfo);
	}
	
});	
function getPandianPingjiaItem(){
	showloading();
	$.ajax({  
		url: "../pandianevery/getPandianPingjiaItem"
		,type:'post'
		,async: false
		,contentType: "application/json; charset=utf-8"
		,data:JSON.stringify({"flag":0}) 
		,dataType:'json'
		,success: function(res){
			console.log(res);
			try {
				if(res.success){
					var data = res.data;
					addPingjiaItem(data);
				}else{
					layer.msg(res.message);
				}
			} catch (e) {
				console.log(e)
			} finally{
				hideloading();
			}
			
		}
	});
}
function getPandianPingjia(){
	$.ajax({  
		url: "../pandianevery/getPandianJianchaPingjia"
		,type:'post'
		,async: false
		,contentType: "application/json; charset=utf-8"
		,data:JSON.stringify({"pandianid":pandianid}) 
		,dataType:'json'
		,success: function(res){
			try {
				if(res.success){
					var data = res.data;
					addPingjiaItem(data);
				}else{
					layer.msg(res.message);
				}
			} catch (e) {
				console.log(e)
			} finally{
				hideloading();
			}
		}
	});
}
function saveInfo(){
	showloading();
	try {
		var imgStr = "";
		var sendData = {};
		var insertArray = [];
		var checkFlag = true;
		$('#f_div').find('div[jsonKey]').each(function(j,el){
			console.log(el)
			var insertJson = {};
			if($(el).attr('pingjiascore') == '0'){
				alert($(el).parent().find('h5').text()+"还没有评价");
				checkFlag = false;
				return false;
			}else{
				insertJson.pandianid = pandianid;
				insertJson.lrr = userId;
				insertJson.shopcode = shopcode;
				insertJson.pingjiaitem = $(el).attr('pingjiaitem');
				insertJson.pingjiaitemname = $(el).attr('pingjiaitemname');
				insertJson.pingjiaitemscore = $(el).attr('pingjiaitemscore');
				insertJson.pingjiascore = $(el).attr('pingjiascore');
				insertJson.sort = $(el).attr('sort');
				insertJson.pingjiaremark = $('#pingjiaremark').val();
				insertArray.push(insertJson);
			}
		});
		console.log(sendData);
		if(checkFlag){
			sendData.dataArray = insertArray;
			$.ajax({
				url: "../pandianevery/replacePandianJianchaPingjia"
				,type:'post'
				,dataType:'json'
				,async: false
				,contentType: "application/json; charset=utf-8"
				,data:JSON.stringify(sendData) 
				,success: function(res){
					console.log(res)
					if(res.success){
//						history.go(-1);
						window.location.href='toPandian_daibanshixiang';
					}else{
						hideloading();
						layer.alert(res.message);
					}
				}
		    });
		}
/*		console.log(insertArray.length);*/
	} catch (e) {
		console.log(e)
	} finally{
		hideloading();
	}	
	
}	

function addPingjiaItem(jsonparse){
	var itemStr = '';
	$('#f_div').append('<div class="col_box">'
			+'<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_mar_tb7p">'
			+'<h5 id="wentishuomingTitle" class="black">评价</h5>'
//			+'<div deleteIndex="'+thenum+'" class="bt_delete bg_orange">删除</div><div class="clearfix"></div>'
			+'</div>');
	for(var i = 0 ;i<jsonparse.length;i++){
		var id = jsonparse[i].pingjiaitem;
		$('#f_div').append('		<div class="widget-box add_mar_tb7p">'
			+'			<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_bor_tbgrey">'
			+'				<h5><i class="iconfont">&#xe600;</i>&nbsp;'+jsonparse[i].pingjiaitemname+'</h5><span class="red" bitian></span>'
			+'				<div id="star'+id+'" sort="'+jsonparse[i].sort+'" jsonKey="pingjiaitem" pingjiaitem="'+id+'" pingjiaitemname="'+jsonparse[i].pingjiaitemname+'" pingjiaitemscore="'+jsonparse[i].pingjiaitemscore+'" pingjiascore="0" class="pull-right add_bor_none" style="width: 50%;margin-right: 2%; color:#474747; line-height:26px;">'
			+'				</div>'
			+'			</div>'
			+'		</div>');
		if(jsonparse[i].pingjiascore == undefined){
			rate.render({
				elem: '#star'+id
				,text: false
				,choose: function(value){
					var key = this.elem.selector;
					$(key).attr('pingjiascore',value);
				}
			})
		}else{
			rate.render({
				elem: '#star'+id
				,text: false
				,readonly: true
				,value:jsonparse[i].pingjiascore
			})
		}
	}
	$('#f_div').append('		<div class="widget-box add_mar_tb7p">'
						+'			<div class="widget-header widget-header-flat widget-header-small add_pad_tb10p add_bor_tbgrey">'				
						+'				<h5><i class="iconfont">&#xe600;</i>&nbsp;评价内容</h5><span class="red"></span>'						  
						+'			</div>'				
						+'			<div class="widget-body zhediebox1">'					
						+'				<div class="widget-main pd_div" style="padding:0;">'					
						+'					<div class="clearfix jy_div" style="padding:0;">'						
						+'						<textarea id="pingjiaremark"  jsonKey="pingjiaremark" name="pingjiaremark" rows="" cols="" class="pull-left add_pad_tb10p add_bor_none" placeholder="说说他的亮点和不足吧"></textarea>'								
						+'					</div>'						
						+'				</div>'						
						+'			</div>'					
						+'		</div>'			
						+'</div>');
	if(jsonparse[0].pingjiaremark != undefined){
		$('#pingjiaremark').val(jsonparse[0].pingjiaremark);
		$('#pingjiaremark').attr('readonly','readonly');
	}
}
//打开钉钉拍照
function openphoto(){
	if(_config == undefined){
		//alert(sessionStorage.getItem("corp"))
		$.ajax({
			type : "post",
			data:JSON.stringify({"pageUrl":location.href.replace(/\\&/g,'%26'),"corp":sessionStorage.getItem("corp")}),
			contentType: "application/json; charset=utf-8",
			async: false,
			url : "../dingding/getconfig",
			dataType : "json",
			success : function(suc){
				_config = suc.config;		
			}	
		}); 
		dd.config({
			agentId : _config.agentid,
			corpId : _config.corpId,
			timeStamp : _config.timeStamp,
			nonceStr : _config.nonceStr,
			signature : _config.signature,
			jsApiList : [ 'runtime.info','biz.util.uploadImage' ]
		});
	}
	dd.ready(function(){
		dd.biz.util.uploadImage({
		    compression: false,//(是否压缩，默认为true)
		    quality: 100, // 图片压缩质量, 
		    resize: 100, // 图片缩放率
		    stickers: {   // 水印信息
		        time: getNowFormatDateTime(),
		        username: username
		    },
		    onSuccess : function(result) {
			faultphoto.push(result[0]);
			$('#faultpicUrl').append('<div class="w50p h50p add_bor_gray add_rad_4p add_pos_re ">'+
									'<img class="w100 h100 add_rad_4p" src="'+result[0]+'" onclick="showAllPic(\''+result[0]+'\')" />'+
									'<div class="w20p h20p align_center add_pos_ab ab_t0r0 bg_black_opacity white fs_18p add_rad_04p010p" onclick="deletePhoto(this)">×</div>'+
									'</div>'
									);
		    },
		    onFail : function(err) {
			// alert(err)
			}
		});
	});
	dd.error(function(err) {
		alert('dd error: ' + JSON.stringify(err));
	});
}
//预览图片
function showAllPic(imgOne){
	dd.biz.util.previewImage({
		urls: faultphoto,//图片地址列表
		current: imgOne,//当前显示的图片链接
		onSuccess : function(result) {
			/**/
		},
		onFail : function(err) {}
	})
}	
function change(id){
	var theid = 'label'+id;
	if($('#'+theid)[0].className=='add_inlblo flo_left h26p add_pad_lr3 add_rad_4p fs_13p add_mar_r2 add_mar_t2 add_bor_gray gray'){
		$('#'+theid)[0].className='add_inlblo flo_left h26p add_pad_lr3 add_rad_4p fs_13p add_mar_r2 add_mar_t2 add_bor_orange orange';
	}else{
		$('#'+theid)[0].className='add_inlblo flo_left h26p add_pad_lr3 add_rad_4p fs_13p add_mar_r2 add_mar_t2 add_bor_gray gray';
	}
}
//删除图片
function deletePhoto(obj){
	dd.device.notification.confirm({
	    message: "删除图片吗",
	    title: "提示",
	    buttonLabels: ['是', '否'],
	    onSuccess : function(result) {
	    	if(result.buttonIndex == '0'){
	    		var index = $(obj).parent().index()-1;
	    		$(obj).parent().remove();
	    		faultphoto.splice(index,1);
				
	    	}
	    },
	    onFail : function(err) {}
	});
	 
}